import csv
import json


def main(csv_string):
    lines = csv_string.strip().split('\n')
    reader = csv.reader(lines)
    data = [row for row in reader]

    # 转换数值（除表头行和第一列外）
    for row in data[1:]:
        for i in range(1, len(row)):
            try:
                row[i] = float(row[i])
            except ValueError:
                pass

    cols = len(data[0])
    rows = len(data) - 1

    echarts_config = {
        "legend": {},
        "tooltip": {},
        "toolbox": {
            "feature": {
                "saveAsImage": {
                    "title": "下载图表",
                    "type": "png",
                    "name": "chart"
                }
            }
        },
        "dataset": {
            "source": data
        },
        "xAxis": [
            {
                "type": "category",
                "gridIndex": 0,
                "data": data[0][1:]  # 列标签（排除第一列）
            },
            {
                "type": "category",
                "gridIndex": 1,
                "data": [row[0] for row in data[1:]]  # 行标签（第二行之后的第一列）
            }
        ],
        "yAxis": [
            {"type": "value", "gridIndex": 0},
            {"type": "value", "gridIndex": 1}
        ],
        "grid": [
            {"bottom": "55%"},
            {"top": "55%"}
        ],
        "series": []
    }

    # 行方向的柱状图系列（每行生成一个系列）
    row_series = []
    for row in data[1:]:
        row_series.append({
            "type": "bar",
            "seriesLayoutBy": "row",
            "name": row[0],
            "xAxisIndex": 0,
            "yAxisIndex": 0
        })

    # 列方向的柱状图系列（每列生成一个系列，排除第一列）
    col_series = []
    for col_idx in range(1, cols):
        col_series.append({
            "type": "bar",
            "seriesLayoutBy": "column",
            "name": data[0][col_idx],
            "xAxisIndex": 1,
            "yAxisIndex": 1
        })

    echarts_config["series"] = row_series + col_series

    output = "\n```echarts\n" + json.dumps(echarts_config, indent=2, ensure_ascii=False) + "\n```"
    return {"output": output}